$(function(){
  const form = layui.form
  const token = localStorage.getItem('Atoken')
  console.log('token', token)

  if(token === '') {
    layer.msg('请先登录')
  return $('.slinks').html(`<a href="login.html"><i class="fa fa-hand-o-right"></i>&nbsp;登录</a> |
  <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</a>`)
  } else{
    $.ajax({
      method: 'POST',
      url: '/user/getUserInfo',
      success: function(res) {
        console.log(res);
        const user = res.data.userInfo.username || res.data.userInfo.mobile
        $('.slinks').html(`<a data-v-697ed175="" href="#/user" class="router-link-exact-active router-link-active" aria-current="page">
        <i data-v-697ed175="" class="fa fa-user"></i>&nbsp; 您好${ user }，</a>
        <a data-v-697ed175="" class="fa fa-sign-out"></a>
        `)
       $('.user-info .text h3').html(`昵称 ${ user }<span><b>个性宣言</b>:${res.data.userInfo.notes ? res.data.userInfo.notes : '走自己的路，让人说去吧'}</span>`)
      }
    })
    
  }
  
  // 点击退出登录
  $('.slinks').on('click', '.fa', function(){
    location.href = './login.html'
    localStorage.removeItem('token')
  })

  $('#file1').on('change', function(){
    const files = $('#file1')[0].files
    if (files.length <= 0) return alert('请上传')
    const fd = new FormData()
    fd.append('avatar', files[0])
    // console.log(files);
    const urlImg = URL.createObjectURL(files[0])
    $('.form-input img').attr('src', urlImg)
  })

  $('.form-input img').on('click',function(){
    $('#file1').click()
    
  })
  form.render()

  $.ajax({
    method: 'POST',
    url: '/user/getUserInfo',
    success: function(res) {
      // console.log(res.data.userInfo.icon);
      form.val('q',res.data.userInfo)
    }
  })
  
  $('#form-submit').on('submit',function(e){
    e.preventDefault()
    console.log($(this).serialize());
    const fd = form.val('q')
    console.log('fd', fd)
    $.ajax({
      method: 'POST',
      url: '/user/update',
      contentType: 'application/json',
      // processData: false,
      data:JSON.stringify(fd),
      success: function(res) {
        console.log(res);
        if(res.errno !== 0) return layer.msg(res.errmsg)
        layer.msg(res.errmsg)
      }
    })
  })
})